package com.xw.Listener;

import java.security.Security;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.xw.Task.GetMailTask;

/**
 * 服务器启动监听，加载邮箱配置，存储邮箱访问session
 * @author YangJianquan
 */
@Component
public class ServerStartListener implements ServletContextListener, ApplicationContextAware{

	private static Logger logger = LoggerFactory.getLogger(ServerStartListener.class);
	
	private static ApplicationContext context;
	
	@Override
	public void contextDestroyed(ServletContextEvent context) {
		logger.debug("服务器关闭！");
	}

	@Override
	public void contextInitialized(ServletContextEvent context) {
		logger.info("服务器启动！");
		// 获取当前路径
		//初始化获取邮件配置
		initGetMailConfAndStart();  

	}

	/**
	 * 读取配置文件获取邮箱相关的配置信息
	 */
	private void initGetMailConfAndStart() {
		GetMailTask gmt = context.getBean("getMailTask", GetMailTask.class);
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		//判断是否需要开启邮件收取任务
		if (gmt.checkIsNeedToFatchMailWhenStart()) {
			//启动邮件获取任务
			gmt.start();
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		context = ctx;
	}
	
}
